package com.company;
import com.mongodb.Block;f
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.jetbrains.annotations.NotNull;

import java.util.Date;

public class MongoDBTest {
    public static MongoClient mongoClient;
    /**
     * 获取students数据库中名为log的collection对象，
     * @return
     */
    public static MongoCollection<Document> getCollection(){
        mongoClient = new MongoClient("localhost", 27017);
        MongoCollection<Document> collection = mongoClient.getDatabase("students").getCollection("log");
        return collection;
    }

    /**
     * trans form a Log to a mongodb document
     * @param log Log instance to trans form
     * @return trans formed document
     */
    private static Document convertDoc(Log log){
        Document d = new Document("level",log.getLevel())
                .append("stackTrace",log.getStackTrace())
                .append("message",log.getMessage())
                .append("createTime",log.getCreatedTime().toString());
        return d;
    }

    /**
     * insert one log
     */
    public static void saveLog(@NotNull MongoCollection<Document> doc, Log log ) {
        doc.insertOne(convertDoc(log));
    }

    /**
     * @return generated log
     */
    public static Log initLog() {
        Log l = new Log();
        l.setCreatedTime(new Date());
        l.setLevel("Error");
        l.setMessage("this is a test log for development perpose");
        l.setStackTrace("here is some stack trace ...");
        return l;
    }


    public static void queryMongoDBALL(MongoCollection<Document>  col) {
        FindIterable <Document> iter = col.find();
        iter.forEach(new Block<Document>() {
                         @Override
                         public void apply(Document document) {
                             System.out.println(document.toJson());
                         }
                     }
        );
    }
    public static void closeMongoClient() {
        mongoClient.close();
    }



}
